package com.demo.web;

import com.demo.service.StudentService;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;


@WebServlet("/DelServlet")
public class DelServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            req.setCharacterEncoding("UTF-8");
            resp.setContentType("text/html;charset=utf-8");

            String id = req.getParameter("id");
            boolean flag = new StudentService().delete(id);

            //4.创建一个Map对象,给map中设置内容
            Map<String, Object> map = new HashMap<String, Object>();

            if (flag) {
                map.put("isDel", true);
                map.put("msg", "删除成功");
            } else {
                map.put("isDel", false);
                map.put("msg", "删除失败");
            }
            //5.map转成json返回给前台.
            ObjectMapper om = new ObjectMapper();
            String mapJson = om.writeValueAsString(map);

            //6.json数据返回给前台
            resp.getWriter().println(mapJson);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
